//
//  BYBundleSubject.swift
//  BYScan
//
//  Created by yetupal on 2023/6/29.
//

import UIKit
import AudioToolbox

class BYBundleSubject: NSObject {
    
    /// 获取模块名称
    static var modelName: String {
        return NSStringFromClass(Self.classForCoder()).shear_front(c: ".")
    }
    /// 模块类名获取
    static var className: String {
        return NSStringFromClass(Self.classForCoder()).shear_after(c: ".")
    }
    
    /// 获取资源包 & 特别说明 组件模块和资源包bundle名称需要对应
    static var forBundle: Bundle? {
        let tpClass: AnyClass = Self.classForCoder()
        // 生成名称带xx-xx framework 会变成下划线`_`而资源包不会
        let tpModelName = Self.modelName.replacingOccurrences(of: "_", with: "-")
        let tpURL = Bundle(for: tpClass).url(forResource: tpModelName, withExtension: "bundle")
        if let bURL = tpURL {
            return Bundle(url: bURL)
        } else {
            return nil
        }
    }

    static func askImage(name: String) -> UIImage? {
        // 主工程有图片 & 优先加载主工程
        if let kImage = UIImage(named: name) {
            return kImage
        }
        // 加载子模块图片
        if #available(iOS 13.0, *) {
            return UIImage(named: name, in: Self.forBundle, with: nil)?.withRenderingMode(.alwaysOriginal)
        } else {
            return UIImage(named: name, in: Self.forBundle, compatibleWith: nil)?.withRenderingMode(.alwaysOriginal)
        }
    }
    
    // 播放音乐
    static func playMusic() -> Void {
        var soundID: SystemSoundID = 0
        let soundFile = Self.forBundle?.path(forResource: "scanSound", ofType: "wav")
        print("音乐文件路径 => \(soundFile)")
        //生成系统声音
        AudioServicesCreateSystemSoundID(NSURL.fileURL(withPath: soundFile!) as  CFURL, &soundID)
         //播放提示音 带有震动
        //      AudioServicesPlayAlertSound(soundID)
         //播放系统提示
         AudioServicesPlaySystemSound(soundID)
    }
}

// 加载模块图片
func bbModularImage(_ imageName: String) -> UIImage? {
    return BYBundleSubject.askImage(name: imageName)
}


// MARK: - 扩展场景方法
extension UIScreen {
 
    /// 安全区尺寸
    static var safeFrame: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            let window: UIWindow =  UIApplication.shared.delegate?.window as? UIWindow ?? UIWindow()
            return window.safeAreaInsets
        } else {
            return UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        }
    }
}

fileprivate extension String {
    // 截取某个字符之前数据
     func shear_front(c: String) -> String {
        guard let r =  self.range(of: c) else { return "" }
        return String(self[self.startIndex ..< r.lowerBound])
    }
    
    // 截取某个字符之后数据
     func shear_after(c: String) -> String {
        guard let r =  self.range(of: c) else { return "" }
        return String(self[r.upperBound ..< self.endIndex])
    }
    
}
